<template lang="">
    <div>
        <el-form label-width="80px" :model="ques" :rules="rule" ref="ques">
            <el-form-item label="题目" prop="queQue">
                <el-input v-model="ques.queQue"></el-input>
            </el-form-item>
            <el-form-item label="选项">
                <div v-for="(item, index) in ques.queOption" :key="index">
                    <span class="item">{{item}}</span>
                    <el-button type="text" class="add-opt-buttons" v-show="!isAdding" @click="changeOpt(index)">修改选项
                    </el-button>
                    <el-button type="text" class="add-opt-buttons" v-show="!isAdding" @click="deleteOpt(item)">删除选项
                    </el-button>
                </div>
            </el-form-item>
        </el-form>
        <div class="add-opt">
            <el-input class="add-opt-text" v-model="addOptText" v-show="isAdding" @keyup.enter.native="finishAdd"
                placeholder="按下回车或点击下方按钮确认添加" ref="addOptButton"></el-input>
            <span>
                <el-button type="text" class="add-opt-buttons" :disabled="optNum" v-show="!isAdding" @click="addOpt">
                    添加选项</el-button>
            </span>
            <span>
                <el-button type="text" class="add-opt-buttons text-err" v-show="isAdding" @click="isAdding = false">
                    取消添加
                </el-button>
            </span>
            <span>
                <el-button type="text" class="add-opt-buttons confirm-add-opt" v-show="isAdding" @click="finishAdd">
                    确认添加</el-button>
            </span>
        </div>
    </div>
</template>
<script>
    export default {
        name: 'DropUpdate',
        data() {
            return {
                ques: {
                    queQue: '',
                    queOption: [],
                    queType: 4
                },
                rule: {
                    queQue: { required: true, message: '请输入题目', trigger: 'blur' }
                },
                isAdding: false,
                addOptText: '',
                queId: '',
            }
        },
        props: ['question','isEditQues'],
        computed: {
            optNum() {
                if (this.ques.queOption.length < 8) {
                    return false
                } else {
                    return true
                }
            }
        },
        methods: {
            addOpt() {                              //添加一个选项
                this.isAdding = true
                this.$nextTick(() => {
                    this.$refs['addOptButton'].focus()
                })
            },
            finishAdd() {                           //完成选项添加
                if (this.addOptText == '') {
                    this.$message({
                        message: '请填写选项内容',
                        type: 'warning'
                    });
                } else {
                    this.ques.queOption.push(this.addOptText)
                    this.addOptText = ''
                    this.isAdding = false
                }
            },
            deleteOpt(index) {                      //删除选项
                this.ques.queOption.splice(this.ques.queOption.indexOf(index), 1);
            },
            changeOpt(index) {
                this.$prompt('请输入新选项内容', '修改', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(({ value }) => {
                    if (value == null) {
                        this.$message({
                            message: '修改失败：空白的新内容',
                            type: 'error'
                        });
                    } else {
                        let text = value
                        this.$set(this.ques.queOption, index, text)
                    }
                }).catch(() => {

                });
            },
            elementMessage(result) {
                if (result == 0) {
                    this.$message({
                        message: '修改失败',
                        type: 'error'
                    });
                } else {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                }
            },
            emitServer() {
                this.$refs['ques'].validate((valid) => {
                    if (valid) {
                        if (this.ques.queOption.length <= 1) {
                            this.$message({
                                message: '请添加至少两个选项',
                                type: 'warning'
                            });
                        } else {



                            if(this.isEditQues == true){                                        //根据环境切换url发送位置
                                var url = '/question/updateQuestion'
                            }else if(this.isEditQues == false){
                                var url = '/questionBank/updateQuestion'
                            }

                            

                            let queOption = {                           //后端更改了接口元素，以下准备将数组转换为对象---------
                                queOptionA: '',                                                                             //
                                queOptionB: '',                                                                             //
                                queOptionC: '',                                                                             //
                                queOptionD: '',                                                                             //
                                queOptionE: '',                                                                             //
                                queOptionF: '',                                                                             //
                                queOptionG: '',                                                                             //
                                queOptionH: '',                                                                             //
                            }                                                                                               //
                            let i = 0;                                                                                      //
                            let queOptionArr = this.ques.queOption                                                          //
                            for (let item in queOption) {                                                                   //
                                queOption[item] = queOptionArr[i]                                                           //
                                i++                                                                                         //
                            }                                           //转换结束，屎码+1-----------------------------------
                            let ques = Object.assign({},this.ques)  //浅拷贝
                            // let ques = {...this.ques}   //浅拷贝拷贝

                            delete ques.queOption   //删除不需要的元素  //上一行使用的是引用赋值，所以会出问题

                            let result = { ...ques, ...queOption }  //封装最后结果，准备发送
                            this.ques.queType = 0
                            console.log('result', result);
                            axios({
                                method: 'POST',
                                url: url,
                                withCredentials: true,
                                data: JSON.stringify(result),
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            }).then((result) => {
                                this.elementMessage(result.data)
                                this.$bus.$emit('addQuesSuccess')   //告知添加成功
                            }).catch((err) => {
                                this.$message(err.message);
                            });
                        }
                    } else {
                        return false;
                    }
                });
            }
        },
        mounted() {
            this.ques.queId = this.question.queId
            this.ques.queQue = this.question.queQue

            let obj = this.question //引用赋值
            let queOptions = {
                queOptionA: '',
                queOptionB: '',
                queOptionC: '',
                queOptionD: '',
                queOptionE: '',
                queOptionF: '',
                queOptionG: '',
                queOptionH: '',
            }

            for (let key in obj) {
                if (queOptions.hasOwnProperty(key)) {
                    this.ques.queOption.push(obj[key])
                }
            }

            console.log(this.ques.queOption);

            this.$bus.$on('updateDrop', () => {
                this.emitServer()
            })

        },
        beforeDestroy() {
            this.$bus.$off('updateDrop')
        },
    }
</script>
<style scoped>
    .add-opt {
        padding: 0px 50px;
    }

    .text-err {
        color: #F56C6C;
    }

    .confirm-add-opt {
        margin-left: 20px;
    }

    .item{
        margin-right: 30px;
    }
</style>